package com.example.jobtask.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.example.jobtask.dto.LoginRequest;
import com.example.jobtask.dto.RegisterRequest;
import com.example.jobtask.dto.UserInfoResponse;
import com.example.jobtask.service.SysUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AuthController {
    
    @Autowired
    private SysUserService userService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@Valid @RequestBody LoginRequest loginRequest, 
                                                   HttpServletRequest request) {
        try {
            Map<String, Object> result = userService.login(loginRequest, request);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResult);
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            Map<String, Object> result = userService.register(registerRequest);
            result.put("success", true);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResult);
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    @SaCheckLogin
    public ResponseEntity<Map<String, Object>> logout() {
        try {
            Map<String, Object> result = userService.logout();
            result.put("success", true);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResult);
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/userinfo")
    @SaCheckLogin
    public ResponseEntity<Map<String, Object>> getUserInfo() {
        try {
            UserInfoResponse userInfo = userService.getCurrentUserInfo();
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("userInfo", userInfo);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResult);
        }
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    @SaCheckLogin
    public ResponseEntity<Map<String, Object>> changePassword(@RequestBody Map<String, String> request) {
        try {
            String oldPassword = request.get("oldPassword");
            String newPassword = request.get("newPassword");
            
            if (oldPassword == null || newPassword == null) {
                throw new RuntimeException("参数不完整");
            }
            
            Map<String, Object> result = userService.changePassword(oldPassword, newPassword);
            result.put("success", true);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResult);
        }
    }
    
    /**
     * 更新用户信息
     */
    @PostMapping("/update-profile")
    @SaCheckLogin
    public ResponseEntity<Map<String, Object>> updateProfile(@RequestBody Map<String, String> request) {
        try {
            String realName = request.get("realName");
            String phone = request.get("phone");
            String avatar = request.get("avatar");
            
            Map<String, Object> result = userService.updateUserInfo(realName, phone, avatar);
            result.put("success", true);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResult);
        }
    }
    
    /**
     * 检查登录状态
     */
    @GetMapping("/check-login")
    public ResponseEntity<Map<String, Object>> checkLogin() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("isLogin", StpUtil.isLogin());
        
        if (StpUtil.isLogin()) {
            result.put("userId", StpUtil.getLoginId());
            result.put("tokenValue", StpUtil.getTokenValue());
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取Token信息
     */
    @GetMapping("/token-info")
    @SaCheckLogin
    public ResponseEntity<Map<String, Object>> getTokenInfo() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("userId", StpUtil.getLoginId());
        result.put("tokenValue", StpUtil.getTokenValue());
        result.put("tokenTimeout", StpUtil.getTokenTimeout());
        result.put("sessionTimeout", StpUtil.getSessionTimeout());
        
        return ResponseEntity.ok(result);
    }
}